package com.coolshark.shop.controller;

import com.coolshark.shop.entity.Product;
import com.coolshark.shop.mapper.ProductMapper;
import org.apache.ibatis.annotations.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/product")
public class ProductController {
    @Value("${dirPath}") //从application.properties配置文件中获取配置详细
    private String dirPath;

    @Autowired
    ProductMapper mapper;

    @RequestMapping("/insert")
    public void insert(@RequestBody Product product) {
        System.out.println("product = " + product);
        //设置时间
        product.setCreated(new Date());
        mapper.insert(product);
    }

    @RequestMapping("/select")
    public List<Product> select() {
        System.out.println();
        return mapper.select();
    }

    @RequestMapping("/delete")
    public void delete(int id) {
        //得到图片的url
        String url = mapper.selectUrlById(id);
        //删除文件
        new File(dirPath + url).delete();
        //删除数据
        mapper.deleteById(id);
    }

    @RequestMapping("/select/index")
    public List<Product> selectIndex(){
        return mapper.selectIndex();
    };

    @RequestMapping("/select/top")
    public List<Product> selectTop(){
        return mapper.selectTop();
    }

    @RequestMapping("/selectById")
    public Product selectById(int id, HttpSession session){
        //从会话对象中获取和当前商品相关的信息
        String info = (String) session.getAttribute("view"+id);
        //如果没有获取到 代表之前没有浏览过
        if (info==null){
            //往会话对象中保存和当前商品相关的信息
            session.setAttribute("view"+id,"visited");
            //让浏览量+1
            mapper.updateViewCount(id);
        }
        return mapper.selectById(id);
    }

    @RequestMapping("/selectByCid")
    public List<Product> selectByCid(int id) {
        System.out.println("id = " + id);
        return mapper.selectByCid(id);
    }

    @RequestMapping("/selectByWd")
    public List<Product> selectByWd(String wd){
        System.out.println("wd = " + wd);
        return mapper.selectByWd(wd);
    }

    @RequestMapping("/update")
    public void update(@RequestBody Product product){
        System.out.println("Product = " + product);
        mapper.update(product);
    }

}
